using Godot;
using System;

public partial class Main : Godot.Node
{
	[Export]
	public PackedScene MobScene { get; set; }

	private int _score;
	
public override void _Ready()
{
	//NewGame();
	// Note that for calling Godot-provided methods with strings,
// we have to use the original Godot snake_case name.
GetTree().CallGroup("mobs", Node.MethodName.QueueFree);
}
	
public void GameOver()
{
	GetNode<Timer>("MobTimer").Stop();
	GetNode<Timer>("ScoreTimer").Stop();
	GetNode<HUD>("HUD").ShowGameOver();
	//播放音乐
	GetNode<AudioStreamPlayer>("Music").Stop();
	GetNode<AudioStreamPlayer>("DeathSound").Play();
}

public void NewGame()
{
	//初始化
	_score = 0; //分数
	//起始位置
	var player = GetNode<Player>("Player");
	var startPosition = GetNode<Marker2D>("StartPosition");
	player.Start(startPosition.Position);
	//开启定时器
	GetNode<Timer>("StartTimer").Start();
	
	var hud = GetNode<HUD>("HUD");
	hud.UpdateScore(_score);
	hud.ShowMessage("Get Ready!");
	//播放音乐
	GetNode<AudioStreamPlayer>("Music").Play();
}

private void OnScoreTimerTimeout()
{
	_score++;
	GetNode<HUD>("HUD").UpdateScore(_score);
}

private void OnMobTimerTimeout()
{
	// Create a new instance of the Mob scene.
	Mob mob = MobScene.Instantiate<Mob>();

	// Choose a random location on Path2D.
	var mobSpawnLocation = GetNode<PathFollow2D>("MobPath/MobSpawnLocation");
	mobSpawnLocation.ProgressRatio = GD.Randf();

	// Set the mob's direction perpendicular to the path direction.
	float direction = mobSpawnLocation.Rotation + Mathf.Pi / 2;

	// Set the mob's position to a random location.
	mob.Position = mobSpawnLocation.Position;

	// Add some randomness to the direction.
	direction += (float)GD.RandRange(-Mathf.Pi / 4, Mathf.Pi / 4);
	mob.Rotation = direction;

	// Choose the velocity.
	var velocity = new Vector2((float)GD.RandRange(150.0, 250.0), 0);
	mob.LinearVelocity = velocity.Rotated(direction);

	// Spawn the mob by adding it to the Main scene.
	AddChild(mob);
}

private void OnStartTimerTimeout()
{
	GetNode<Timer>("MobTimer").Start();
	GetNode<Timer>("ScoreTimer").Start();
}
}
